<template>
  <!-- 树形 -->
  <el-dialog v-model="isOpen" title="权限设置" width="1000" :before-close="handleClose">
    <el-tree
        v-loading="loading"
        style="height: 500px; overflow-y: scroll"
        ref="treeRef"
        :data="props.options"
        show-checkbox
        node-key="value"
        default-expand-all
        :expand-on-click-node="false"
        @check-change="nodeChange"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node" @click.stop>
          <span>{{ node.label }}</span>
          <el-checkbox-group
              v-if="data.children.length == 0"
              v-model="selectPower[data.value]"
              size="small"
              @change="powerChange($event, data.value)"
          >
            <el-checkbox-button v-for="item in props.gridFunctuin" :key="item" :value="item">
              {{ item }}
            </el-checkbox-button>
          </el-checkbox-group>
        </span>
      </template>
    </el-tree>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="selectOk">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, inject, onBeforeMount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
const api = inject('api')
const roleMenuApi = api.getApi('FaSysRoleMenu', null)
const data = defineModel()
const props = defineProps(['options', 'gridFunctuin'])
const emit = defineEmits(['editOk'])
const isOpen = ref(true)
const loading = ref(false)
const selectPower = ref({})
const treeRef = ref(null)
const defaultCheckedKeys = ref([])

onBeforeMount(() => {
  loading.value = true
  load()
})
// 初始化
function load() {
  // 获取该角色权限
  roleMenuApi
      .rolePower(data.value.id)
      .then((res) => {
        if (res.code == 200) {
          for (const key in res.data) {
            const item = res.data[key]
            // 设置默认权限
            selectPower.value[item.menuId] = JSON.parse(item.functionRole)
            // 排除父节点,设置父节点会自动连子节点一起设置
            let options = props.options.filter((option) => option.id == item.menuId)
            if (options.length == 0) {
              // 设置默认选中节点
              defaultCheckedKeys.value.push(item.menuId)
            }
          }
          // 设置默认选中节点
          treeRef.value.setCheckedKeys(defaultCheckedKeys.value)
        }
      })
      .finally(() => {
        nextTick(() => {
          loading.value = false
        })
      })
}
// 处理节点选中对应权限默认选中和取消
function nodeChange(data, nodeSelect, childSelect) {
  // 只监听尾节点
  if (data.children.length == 0) {
    // 选中
    if (nodeSelect && !selectPower.value[data.id]?.length != 0) {
      selectPower.value[data.id] = props.gridFunctuin
    } else if (!nodeSelect) {
      // 取消
      selectPower.value[data.id] = []
    }
  }
  // 监听尾节点取消
}
// 权限选择变化
function powerChange(value, menuId) {
  // 只监听第一次选中
  if (value.length === 1) {
    if (!selectPower.value[menuId]?.length != 1) {
      // 设置节点默认选中
      treeRef.value.setChecked(menuId, true, false)
    }
  } else if (value.length === 0) {
    // 设置节点取消
    treeRef.value.setChecked(menuId, false, false)
  }
}

// 设置完成
function selectOk() {
  // 获取选中和半选中节点数组
  const checkedNodes = treeRef.value.getCheckedNodes(false, true)
  let powerSetDatas = []
  checkedNodes.forEach((node) => {
    const functionRoleData = selectPower.value[node.id]
        ? JSON.stringify(selectPower.value[node.id])
        : '[]'
    powerSetDatas.push({
      roleId: data.value.id,
      menuId: node.id,
      functionRole: functionRoleData
    })
  })
  // 设置权限
  roleMenuApi.powerSet(powerSetDatas, data.value.id).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: '设置成功',
        type: 'success'
      })
    }
  })
}
// 叉掉弹出框
function handleClose(done) {
  emit('editOk')
  done()
}
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
